package com.aijk.web.admin.utils;

import com.aijk.ehm.sys.model.SysModule;
import com.aijk.web.admin.entity.JsTree;
import com.aijk.web.admin.entity.JsTreeState;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>  </p>
 * User: chendw
 * Date: 2016/11/23 12:52
 */
public class ModuleTreeUtils {

    public static List<JsTree> getModuleTree(List<SysModule> list, List<Integer> selectedIds) {
        List<JsTree> treedata = new ArrayList<>();
        for (SysModule module : list) {
            //这里需要的是一级菜单的id，对于没有父菜单id的就是一级菜单

            JsTree tree = new JsTree(String.valueOf(module.getId()), module.getTitle());
            if (CollectionUtils.isNotEmpty(selectedIds)) {
                JsTreeState state = new JsTreeState(false, selectedIds.contains(module.getId()));
                tree.setState(state);
            }

            if (0 == module.getPid()) {
                List<JsTree> iterateMenus = iterateMenus(list, module.getId(),selectedIds);
                tree.setChildren(iterateMenus);
                treedata.add(tree);
            }
        }
        return treedata;
    }

    public static List<JsTree> getModuleTree(List<SysModule> list) {
        return getModuleTree(list, null);
    }

    //多级菜单查询方法
    public static List<JsTree> iterateMenus(List<SysModule> moduleList, Integer pid,List<Integer> selectedIds) {
        List<JsTree> result = new ArrayList<>();

        for (SysModule module : moduleList) {
            JsTree tree = new JsTree(String.valueOf(module.getId()), module.getTitle());
            Integer menuid = module.getId();//获取菜单的id
            Integer parentid = module.getPid();//获取菜单的父id
            if (CollectionUtils.isNotEmpty(selectedIds)) {
                JsTreeState state = new JsTreeState(false, selectedIds.contains(module.getId()));
                tree.setState(state);
            }
            if (parentid != null) {
                if (parentid.equals(pid)) {
                    List<JsTree> iterateMenu = iterateMenus(moduleList, menuid,selectedIds);
                    tree.setChildren(iterateMenu);
                    result.add(tree);
                }
            }
        }
        return result;
    }

    //多级菜单查询方法
    public static List<JsTree> iterateMenus(List<SysModule> moduleList, Integer pid) {
       return iterateMenus(moduleList,pid,null);
    }
}
